
import 'dart:async';

import 'package:path_provider/path_provider.dart';
import 'package:record/record.dart';

typedef ValTimerEndListener = void Function();

class ValAudioRecorder {
  ValAudioRecorder._internal();

  static final ValAudioRecorder _instance = ValAudioRecorder._internal();

  factory ValAudioRecorder() => _instance;
  Record? _audioRecorder;
  int _recordDuration = 0;
  Timer? _timer;

  void start() {
    _audioRecorder ??= Record();
    _start();
  }

  Future<void> _start() async {
    try {
      _recordDuration = 0;
      if (await _audioRecorder?.hasPermission() ?? true) {
        // Record to file
        final dir = await getApplicationDocumentsDirectory();
        String path = '${dir.path}/${DateTime.now().millisecondsSinceEpoch}.m4a';
        await _audioRecorder?.start(path: path, encoder: encoder, bitRate: 32000, numChannels: 1, samplingRate: 32000);
        _startTimer();
      }
    } catch (e) {

    }
  }

  Future<void> stop(Function(String path) onStop) async {
    final path = await _audioRecorder?.stop();
    if (path != null) {
      onStop(path);
    }
  }

  int get recordDuration => _recordDuration;

  AudioEncoder get encoder => AudioEncoder.aacLc;

  void _startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      _recordDuration++;
      if (_recordDuration > 59) {
        listener?.call();
      }
    });
  }

  ValTimerEndListener? listener;

  void addTimerListener(ValTimerEndListener listener) => this.listener = listener;

  void dispose() {
    _audioRecorder?.dispose();
  }
}

